package com.hqq.leetcode.dp;

/**
 * MinPathSum  最小路径和
 * Description:
 * Given a m x n grid filled with non-negative numbers,
 * find a path from top left to bottom right which minimizes the sum of all numbers along its path.
 * <p>
 * Tip:
 * dp[i][j] = grid[i][j] + min(dp[i-1][j])
 * Created by heqianqian on 2017/9/15.
 */
public class MinPathSum {

    /*
     * @param grid: a list of lists of integers
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    public int minPathSum(int[][] grid) {
        // write your code here
        //二维数组的行和列数
        int m = grid.length, n = grid[0].length;
        int[][] dp = new int[m][n];//用来存放最小路径和的数组
        dp[0][0] = grid[0][0];//初始最小路径和
        //初始化第一行的最小路径和
        for (int i = 1; i < m; i++) {
            dp[i][0] = grid[i][0] + dp[i - 1][0];
        }
        //初始化第一列的最小路径和
        for (int i = 1; i < n; i++) {
            dp[0][i] = grid[0][i] + dp[0][i - 1];
        }
        //求二维数组中其他元素的最小路径和
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
        return dp[m - 1][n - 1];
    }
}
